package systems;

import java.util.ArrayList;
import java.util.Collections;

import javax.cache.Cache;
import javax.cache.CacheException;
import javax.cache.CacheManager;

public class RecentlyUpdate {
	
	private static String cacheName = "recentlyUpdate";
	
	private static int limit = 50;
	
	public static void insert(String name) {
		Cache cache=null;
    	try {
		    cache = CacheManager.getInstance().getCacheFactory().createCache(Collections.emptyMap());
		} catch (CacheException e1) {
		   e1.printStackTrace();
		}
		
		ArrayList<String> domains = new ArrayList<String>();
		if(cache!=null&&cache.containsKey(cacheName))
		{
			domains = (ArrayList<String>) cache.get(cacheName);
		}
		
		if (domains.contains(name)) {
			domains.remove(name);
		}
		
		if (domains.size() >= limit) {
			domains.remove(limit - 1);
		}
		
		domains.add(0, name);
		
		cache.put(cacheName, domains);
	}
	
	public static ArrayList<String> getDomains() {
		ArrayList<String> domains = new ArrayList<String>();
		
		Cache cache=null;
    	try {
		    cache = CacheManager.getInstance().getCacheFactory().createCache(Collections.emptyMap());
		} catch (CacheException e1) {
		   e1.printStackTrace();
		}
		
		if(cache!=null&&cache.containsKey(cacheName))
		{
			domains = (ArrayList<String>) cache.get(cacheName);
		}
		
		return domains;
	}
}
